package fss.util;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Scanner;

import fss.client.FssClient;
import fss.common.communication.QueryResult;
import fss.core.config.FssProperties;
import fss.remote.FssServer;
import fss.transfer.Transfer;
import fss.transfer.TransferId;
import fss.transfer.TransferSource;
import fss.transfer.TransferType;
import fss.transfer.TransferUtils;
import fss.util.rmi.RmiId;

public class SerializeUtilsTest {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        RmiId clientId = new RmiId("fedbox", "client00", 3000);
        RmiId serverId = new RmiId("fedbox", "server00", 2000);
        RmiId registryId = new RmiId("fedbox", "reg00", 2099);
        FssClient client = new FssClient(clientId);
        FssServer server = new FssServer(serverId, registryId);
        String filename = null;
        
        List<QueryResult> qr = server.getFileList();
        int count = 1;
        for(QueryResult q : qr) {
            System.out.println((++count) + ". " + q);
        }
        System.out.println();
        
        System.out.print("Enter a filename: ");
        filename = in.nextLine();
        
        TransferId id = new TransferId(TransferType.DOWNLOAD);
        id.setDestinationId(clientId);
        id.setSourceId(serverId);
        id.setFilename(filename);
        id.setSourceType(TransferSource.CLIENT);
        
        byte[] data = FssUtils.getFileBytes(null, server.getDatadir() + FssUtils.getSystemFileSeparator() + filename);
        System.out.println("- Data -\n");
        System.out.println(FssUtils.byteArrayToString(data));
        System.out.println("\n- End Data -\n");
        
        Transfer transfer = new Transfer(id);
        transfer.setData(data);
        transfer.setFilesize(data.length);
        transfer.setLastUpdateTimestamp((new UtcDate()).getDate());
        System.out.println("Transfer (before serialized): " + transfer);
        
        String serfilename =  client.getDatadir() + FssUtils.getSystemFileSeparator() + TransferUtils.getTransferFilename(transfer.getId());
        SerializableUtils.serializeObject(transfer,serfilename);
        System.out.println("Transfer serialized to " + serfilename);
        
        String newData = "This is new data to be writen HOHOHO";
        
        Transfer deserializedTransfer = (Transfer) SerializableUtils.deserializeObject(serfilename);
        System.out.println("Transfer (deserialized): " + deserializedTransfer);
        
        TransferUtils.combineTransferData(deserializedTransfer, newData.getBytes());
        System.out.println("\n" + new String(deserializedTransfer.getData()));
        TransferUtils.convertTransferToFile(deserializedTransfer, client.getDatadir());
    }
}
